import utils from './util'
import store from '../store/globalStore'

//微信小程序和APP版本
// #ifndef H5
import Fly from 'flyio/dist/npm/wx'
// #endif

const fly = new Fly()

fly.interceptors.request.use(
    config => {
        const Authorization = store.getters['settings/token']
        const baseUrl = store.getters['settings/baseUrl']
        if (!/^http[s]?\:\/\//.test(config.url)) {
            Object.assign(config, { url: baseUrl + config.url })
        }
        if (Authorization) {
            Object.assign(config.headers, { Authorization })
        }
        return config
    },
    err => {
        console.log('global request error handler', err)
    },
)

fly.interceptors.response.use(
    response => {
        if (response.status == 302 || response.status == 401) {
            console.log('resonpse.status unauthorized code, redirect to login page')
            utils.reLaunch('pages/launch/main')
        }
        return response
    },
    err => {
        utils.showToast('网络连接失败, 请联系管理员')
        console.log('global response error handler', err)
    },
)

export default fly
